package com.eric.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.dto.LocationDto;
import com.eric.domain.po.Location;
import com.eric.mapper.LocationMapper;
import com.eric.service.ILocationService;
import com.eric.utils.RegUtil;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;

/**
 * <p>
 * 所在地，用于存储仓库、项目所在地 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-03-23
 */
@Service
public class LocationServiceImpl extends MPJBaseServiceImpl<LocationMapper, Location> implements ILocationService {
    private final Integer SIGN=0;

    //    存储一条数据
    @Override
    @Transactional
    public SaResult saveOneService(LocationDto locationDto) {

        if (BeanUtil.isEmpty(locationDto)){
            return SaResult.error("数据为空");
        }

//       如果地址名为Null或者为""时，返回错误
        String locationAddress = locationDto.getLocationAddress();
        String trim = StrUtil.trim(locationAddress);

        if (StrUtil.isBlank(trim)){
            return SaResult.error("地址名不能为空");
        }
//        用着则表达式校验地址名
        boolean match = ReUtil.isMatch(RegUtil.realNameRegx, locationAddress);
        if (!match){
            return SaResult.error("地址名格式错误");
        }

//        如果userId为空或者projectId为空同时warehouseId为空或者projectId和warehouseId都不为空，返回错误信息
        if (locationDto.getUserId()==null||
                (locationDto.getProjectId()==null&&locationDto.getWarehouseId()==null)
        ){

            return SaResult.error("数据错误");
        }
//        通过上述校验后，如果projectId为空时，就设定projectId=SIGN值
        if (locationDto.getProjectId()==null){
            locationDto.setProjectId(SIGN);
        }
//        如果warehouseId为空时，设定warehouseId=SIGN值
        if (locationDto.getWarehouseId()==null){
            locationDto.setWarehouseId(SIGN);
        }
//        如果description为null或者""时，返回错误
        String description = locationDto.getDescription();
        String trimDescription = StrUtil.trim(description);
        if (StrUtil.isBlank(trimDescription)){
            return SaResult.error("备注不能为空");
        }
//       根据规则，一个用户只能一个地方，防止材料管理时出现逻辑错误
        Location locationQueryByUserId = query().eq("user_id", locationDto.getUserId()).one();
        if (locationQueryByUserId != null){
            return SaResult.error("用户的Location已存在，不得重复！");
        }

        Location location = BeanUtil.copyProperties(locationDto, Location.class);
        save(location);
        return SaResult.ok();
    }

    @Override
    @Transactional
    public SaResult modifyOneService(LocationDto locationDto) {

        if (BeanUtil.isEmpty(locationDto)){
            return SaResult.error("数据为空");
        }
        if (locationDto.getId()==null){
            return SaResult.error("id为不能空");
        }
//        如果locationAddress为null或者" "时，值设定为null,如果不为空，用正则表达式来校验
        String locationAddress = locationDto.getLocationAddress();

        String trim = StrUtil.trim(locationAddress);

        if (StrUtil.isBlank(trim)){
//            如果trim==null，
            locationDto.setLocationAddress(null);
            return SaResult.error("location address 不能为空");

        }
        boolean match = ReUtil.isMatch(RegUtil.realNameRegx, locationAddress);
        if (!match){
            return SaResult.error("地址格式错误！");
        }


        /*
         * 这里的逻辑与saveOne哪里不一样，首先，projectId或者warehouseId这两个数值肯定是一个为SIGN值
         *
         * */
//        如果projectId和warehouseId都不为空时，这个肯定要返回数据错误
//        但是如果两个都为null时，那个就没问题，不用把这两个字段写入数据库
        if (locationDto.getProjectId()==null&&locationDto.getWarehouseId()==null){
            return SaResult.error("数据错误");
        }
//        如果projectId为空，而warehouse不为空时,把projectId=SIGN
        if (locationDto.getProjectId() == null){
            locationDto.setProjectId(SIGN);
        }
//        如果projectId不为空，而warehouse为空时，把warehouseId=SIGN
        if (locationDto.getProjectId()!=null&&locationDto.getWarehouseId()==null){
            locationDto.setWarehouseId(SIGN);
        }
//        如果description为null或者""时，设定description为null
        String description = locationDto.getDescription();
        String trimDescription = StrUtil.trim(description);
        if (StrUtil.isBlank(trimDescription)){
            locationDto.setDescription(null);
        }

        boolean updated = updateById(BeanUtil.copyProperties(locationDto, Location.class));

        return   updated ? SaResult.ok("修改成功"):SaResult.error("修改失败");
    }

    @Override
//    根据id删除一条数据
    @Transactional
    public SaResult deleteOneLocationByIdService(Integer id) {
        if (id==null){
            return SaResult.error("id不能为空");
        }
        boolean b = removeById(id);

        return b?SaResult.ok("succeed"):SaResult.error("没这行数据");
    }

    @Override
//    分页获取多条数据，pageCount:第几页，pageSize：每页多少条数据
    public SaResult getAllLocationListService(Integer pageCount, Integer pageSize) {
        if (pageCount==null){
            pageCount=PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<Location> page = page(new Page<>(pageCount, pageSize));
        List<Location> locationList = query().orderByDesc("update_time").page(page).getRecords();
        return SaResult.data(BeanUtil.copyToList(locationList,LocationDto.class));
    }

    @Override
//    根据id获取一条信息
    public SaResult getOneByIdService(Integer id) {
        if (id==null){
            return SaResult.error("输入参数不能为空");
        }
        Location location = query().eq("id", id).one();
        LocationDto locationDto = BeanUtil.copyProperties(location, LocationDto.class);
        return SaResult.data(locationDto);
    }

    @Override
    public SaResult getByAddressService(String address,Integer pageCount,Integer pageSize) {
        if (address==null){
            return SaResult.error("参数不能为空");
        }
        String trim = StrUtil.trim(address);
        if (pageCount==null){
            pageCount=PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<Location>page=new Page<>(pageCount,pageSize);
        List<Location> locationAddress = query().like("location_address", trim).orderByDesc("update_time"). page(page).getRecords();
        List<LocationDto> locationDtoList = BeanUtil.copyToList(locationAddress, LocationDto.class);
        return SaResult.data(locationDtoList);
    }

    @Override
    public SaResult getAllByUserIdService(Integer userId,Integer pageCount,Integer pageSize) {
        if (userId==null){
            return SaResult.error("输入参数有误");
        }
        if (pageCount==null){
            pageCount=PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<Location>page=new Page<>(pageCount,pageSize);
        List<Location> locationList = query().eq("user_id", userId).orderByDesc("update_time").page(page).getRecords();
        List<LocationDto> locationDtoList = BeanUtil.copyToList(locationList, LocationDto.class);
        return SaResult.data(locationDtoList);
    }

    @Override
    public SaResult getAllByProjectIdServie(Integer projectId,Integer pageCount,Integer pageSize) {
        if (projectId==null){
            return SaResult.error("输入参数有误");
        }
        if (pageCount==null){
            pageCount=PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<Location>page=new Page<>(pageCount,pageSize);
        List<Location> locationList = query().eq("project_id", projectId).orderByDesc("update_time").page(page).getRecords();
        List<LocationDto> locationDtoList = BeanUtil.copyToList(locationList, LocationDto.class);
        return SaResult.data(locationDtoList);
    }

    @Override
    public SaResult getAllByWarehouseIdServie(Integer warehouseId,Integer pageCount,Integer pageSize) {
        if (warehouseId==null){
            return SaResult.error("输入参数有误");
        }
        if (pageCount==null){
            pageCount= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<Location>page=new Page<>(pageCount,pageSize);
        List<Location> locationList = query().eq("warehouse_id", warehouseId).page(page).getRecords();
        List<LocationDto> locationDtoList = BeanUtil.copyToList(locationList, LocationDto.class);
        return SaResult.data(locationDtoList);
    }

    @Override
    public String getAllByLoginId() {
        String idStr = StpUtil.getLoginId().toString();
        int userId = Integer.parseInt(idStr);
        Location location = query().eq("user_id", userId).one();
        if (location==null){
            return null;
        }
        return location.getLocationAddress();
    }

}
